/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Principal;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author pato
 */
public class ActualizarRegistros extends javax.swing.JFrame {

    /**
     * Creates new form ActualizarRegistros
     */
    String consulta, id;

    public ActualizarRegistros() {
        initComponents();
        this.setLocationRelativeTo(null);
        progreso.setMinimum(0);
    }

    private void volcarDatos() {
        super.setTitle("Actualizacion Paso 1/2");
        try {
            cache_connection.cn.setAutoCommit(false);
            local_connection.cn.setAutoCommit(false);
            PreparedStatement ps = (PreparedStatement) cache_connection.cn.prepareStatement("select count(*)from cache where respaldado = 0");
            ResultSet rs = ps.executeQuery();
            rs.next();
            progreso.setMaximum(rs.getInt(1));
            ps = (PreparedStatement) cache_connection.cn.prepareStatement("SELECT consulta,tabla FROM cache where respaldado = 0 order by tabla desc");
            rs = ps.executeQuery();
            int i = 0;
            while (rs.next()) {
                actualizando.setText("Actualizando:  " + rs.getString(2));
                ps = local_connection.cn.prepareStatement(" " + rs.getString(1) + " ");
                //  System.out.println(rs.getString(1));
                ps.execute();
                progreso.setValue(i++);
            }
            ps = cache_connection.cn.prepareStatement("UPDATE cache SET respaldado = 1");
            ps.execute();
            local_connection.cn.commit();
            cache_connection.cn.commit();
        } catch (SQLException ex) {
            VentanaPrincipal.logger.log(Level.SEVERE, null, ex);
        }
    }

    private void actualizarDatos() {
        try {
            progreso.setValue(0);
            super.setTitle("Actualizacion Paso 2/2");
            String fecha, tabla;
            int i = 0;
            PreparedStatement ps = (PreparedStatement) cache_connection.cn.prepareStatement("select  datetime(fecha, 'localtime') from actualizacion order by id desc limit 1");
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                fecha = rs.getString(1);
            } else {
                fecha = "0000-00-00 00:00:00";
            }
            ps = (PreparedStatement) local_connection.cn.prepareStatement("select count(*)from cambios where fecha >= ? order by tabla");
            ps.setString(1, fecha);
            rs = ps.executeQuery();
            rs.next();
            progreso.setMaximum(rs.getInt("count(*)"));
            ps = (PreparedStatement) local_connection.cn.prepareStatement("select id,consulta,tabla from cambios where fecha >= ? order by tabla");
            ps.setString(1, fecha);
            rs = ps.executeQuery();
            while (rs.next()) {
                tabla = rs.getString("tabla");
                id = rs.getString("id");
                consulta = rs.getString("consulta");
                actualizando.setText("Actualizando:  " + tabla);
                // System.out.println(" "+consulta+" ");
                if (consulta != null) {
                    consulta = consulta.replace(" do ", " select ");
                    consulta = consulta.replace("LIMIT 1", "");
                    try {
                        ps = (PreparedStatement) cache_connection.cn.prepareStatement(" " + consulta + " ");
                        ps.execute();
                    } catch (SQLException ex) {
                        VentanaPrincipal.logger.log(Level.SEVERE, null, ex);
                        VentanaPrincipal.logger.log(Level.SEVERE, null, consulta);
                        System.out.println(consulta + "    " + id);
                    }
                }
                i++;
                ps = (PreparedStatement) cache_connection.cn.prepareStatement("insert into actualizacion (idremoto) values(?)");
                ps.setString(1, id);
                ps.execute();
                progreso.setValue(++i);
                            local_connection.cn.commit();
            cache_connection.cn.commit();
            }


        } catch (SQLException ex) {
            VentanaPrincipal.logger.log(Level.SEVERE, null, ex);
            VentanaPrincipal.logger.log(Level.SEVERE, null, consulta);
            System.out.println(consulta + "    " + id);
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        actualizando = new javax.swing.JLabel();
        progreso = new javax.swing.JProgressBar();
        Aceptar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Actualizando");
        setAlwaysOnTop(true);
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        setResizable(false);

        actualizando.setText("Actualizando ------ ");

        Aceptar.setText("Actualizar");
        Aceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                AceptarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addComponent(progreso, javax.swing.GroupLayout.PREFERRED_SIZE, 237, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(actualizando, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(Aceptar)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(actualizando)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(progreso, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(Aceptar)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void AceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AceptarActionPerformed
        if (Aceptar.getText().equals("Actualizar")) {
            Runnable runner = new Runnable() {
                public void run() {
                    Aceptar.setEnabled(false);
                    volcarDatos();
                    actualizarDatos();
                    actualizarEspeciales();
                    actualizarStock();
                    Aceptar.setEnabled(true);

                }
            };
            Thread t = new Thread(runner, "Code Executer");
            t.start();
        } else {
            this.dispose();
        }
    }//GEN-LAST:event_AceptarActionPerformed
    void actualizarEspeciales() {
        try {
PreparedStatement ps=local_connection.cn.prepareStatement("select * from especiales");
    ResultSet rs=ps.executeQuery();
    ps=cache_connection.cn.prepareStatement("delete from especiales");
    ps.execute();
    ps=cache_connection.cn.prepareStatement("insert into especiales values(null,?,?,?,?,?,?)");
    while(rs.next()){
        ps.setInt(1,rs.getInt("id_producto"));
        ps.setString(2,rs.getString("clave"));
        ps.setInt(3,rs.getInt("sucursal"));
        ps.setString(4,rs.getString("tipo"));
        ps.setString(5,rs.getString("fecha"));
        ps.setInt(6,rs.getInt("vendido"));
        ps.execute();
    }
    local_connection.cn.commit();
            cache_connection.cn.commit();
        } catch (SQLException ex) {
            Logger.getLogger(ActualizarRegistros.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    void actualizarStock() {
        try {
            actualizando.setText("Actualizando Stock");
            int i = 0;
            PreparedStatement ps = (PreparedStatement) cache_connection.cn.prepareStatement("select count(*)from stock where sucursal = ?");
            ps.setInt(1, VentanaPrincipal.sucursal);
            ResultSet rs = ps.executeQuery();
            rs.next();
            progreso.setValue(0);
            progreso.setMaximum(rs.getInt(1));
            ps = (PreparedStatement) local_connection.cn.prepareStatement("select cantidad,id_producto from stock where sucursal = ?");
            ps.setInt(1, VentanaPrincipal.sucursal);
            rs = ps.executeQuery();
            ps = (PreparedStatement) cache_connection.cn.prepareStatement("update stock set cantidad = ? where sucursal = ? and id_producto = ?");
            ps.setInt(2, VentanaPrincipal.sucursal);
            while (rs.next()) {
                ps.setInt(1, rs.getInt(1));
                ps.setInt(3, rs.getInt(2));
                ps.execute();
                progreso.setValue(++i);
            }
                                        local_connection.cn.commit();
            cache_connection.cn.commit();
            cache_connection.cn.setAutoCommit(true);
            local_connection.cn.setAutoCommit(true);
            Aceptar.setText("Cerrar");
            actualizando.setText("Actualizacion terminada");
            super.setTitle("Actualizacion terminada");
        } catch (SQLException ex) {
            Logger.getLogger(ActualizarRegistros.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    /**
     * @param args the command line arguments
     */
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton Aceptar;
    private javax.swing.JLabel actualizando;
    private javax.swing.JProgressBar progreso;
    // End of variables declaration//GEN-END:variables
}
